%%语音信号采集
fs = 8000;          % 采样频率
duration = 2;        % 时间长度(秒） 
n = duration*fs;     % 采样点数
t = (1:n)/fs;
%创建一个录音文件：fs =8000
recObject = audiorecorder(fs, 16, 1);   
fprintf('开始录音:\n');pause(0);
recordblocking(recObject, duration);
stop(recObject);
fprintf('录制结束\n');
play(recObject);        % 播放录制的音频
y = getaudiodata(recObject);
ymax = max(abs(y));      % 归一化
y = y/ymax;
 
%%绘制波形图，见图1
audiowrite('audio1.wav', y, fs);      % 写入音频 
figure(1);
plot(t, y);
xlabel('时间/s');
ylabel('幅度');
title('(a)fs = 8000');
grid;




[x,fs]=audioread('audio1.wav');
fx=fft(x);
figure(2)
plot(abs(fftshift(fx)));

%DWT 一级

figure(3)
[a,fs]=audioread('audio1.wav');
[cal,cd1]=dwt(a(:,1),'db4');
a0=idwt(cal,cd1,'db4',length(a(:,1)));
subplot(4,1,1);plot(a(:,1));
subplot(4,1,2);plot(cd1);
subplot(4,1,3);plot(cal);
subplot(4,1,4);plot(a0);


%DWT 三级
wav_name = 'audio1.wav';
[wav,fs] = audioread(wav_name); % 获得语音信号
len = length(wav); % 语音信号大小
wav_vec = zeros(len,1); % 预分配内存
for i = 1 : len % 语音信号转向量
    wav_vec(i) = wav(i);
end
[c,l] = wavedec(wav_vec,3,'db4'); % 小波基选用 Daubechies-4 小波
ca3 = appcoef(c,l,'db4',3); % 三级分解近似分量
cd3 = detcoef(c,l,3); % 三级分解细节分量
cd2 = detcoef(c,l,2); % 三级分解细节分量
cd1 = detcoef(c,l,1); % 三级分解细节分量
wav0 = waverec(c,l,'db4'); % 逆 dwt
figure(4)
subplot(3,2,1),plot(wav);
subplot(3,2,2),plot(ca3); % 三级分解细节分量
subplot(3,2,3),plot(cd1); % 一级分解近似分量
subplot(3,2,4),plot(cd2); % 二级分解近似分量
subplot(3,2,5),plot(cd3); % 三级分解近似分量
subplot(3,2,6),plot(wav0); % 三级重构
axes_handle = get(gcf, 'children');
axes(axes_handle(6)); title('(1) wav original');
axes(axes_handle(5)); title('(2) 3 detail component');
axes(axes_handle(4)); title('(3) 1 approximation');
axes(axes_handle(3)); title('(4) 2 approximation');
axes(axes_handle(2)); title('(5) 3 approximation');
axes(axes_handle(1)); title('(6) wav recover');


wav_name = 'audio1.wav';
[wav,fs] = audioread(wav_name); % 获得语音信号
len = length(wav); % 语音信号大小
wav_vec = zeros(len,1); % 预分配内存
for i = 1 : len % 语音信号转向量
    wav_vec(i) = wav(i);
end
da = dct(wav_vec); % dct
wav0 = idct(da); % 逆 dct
figure(5)
subplot(3,1,1),plot(wav);
subplot(3,1,2),plot(da); % dct
subplot(3,1,3),plot(wav0); % 重构
axes_handle = get(gcf, 'children');
axes(axes_handle(3)); title('(1) wav original');
axes(axes_handle(2)); title('(2) wav dct');
axes(axes_handle(1)); title('(3) wav recover');